package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.vo.account.AccountLockVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Autowired
    private UserAccountMapper userAccountMapper;

    @Autowired
    private UserAccountDetailMapper userAccountDetailMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Transactional
    @Override
    public void saveAccount(Long userId) {
        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(userId);
        this.save(userAccount);
    }

    @Override
    public BigDecimal getAvailableAmount(Long userId) {
        UserAccount userAccount = userAccountMapper.selectOne(new LambdaQueryWrapper<UserAccount>().eq(UserAccount::getUserId, userId));
        return userAccount.getAvailableAmount();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean checkAndDeductAmount(AccountLockVo accountLockVo) {

        Integer result = userAccountMapper.checkAndDeductAmount(accountLockVo);
        if (result.equals(0)) {
            throw new GuiguException("余额不足,扣除余额失败");
        }
        // 账户余额扣除成功
        // 保存交易流水到数据库
        UserAccountDetail userAccountDetail = new UserAccountDetail();
        userAccountDetail.setUserId(accountLockVo.getUserId());
        userAccountDetail.setAmount(accountLockVo.getAmount());
        userAccountDetail.setOrderNo(accountLockVo.getOrderNo());
        userAccountDetail.setTitle("订单支付"+accountLockVo.getContent());
        userAccountDetail.setAmount(accountLockVo.getAmount());
        userAccountDetail.setTradeType(SystemConstant.ACCOUNT_TRADE_TYPE_MINUS);// 消费类型
        return result>0;
    }

}
